<template>
  <div class="goods-detail-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-section">
      <div class="container">
        <el-breadcrumb separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/goods' }">商品中心</el-breadcrumb-item>
          <el-breadcrumb-item>{{ currentGoods?.goodsName || '商品详情' }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <!-- 商品详情主体 -->
    <div
      class="main-content"
      v-loading="goodsStore.loading"
    >
      <div class="container">
        <!-- 商品信息区域 -->
        <div
          v-if="currentGoods"
          class="product-section"
        >
          <el-row :gutter="48">
            <!-- 商品图片区域 -->
            <el-col
              :span="12"
              :xs="24"
              :sm="24"
              :md="12"
              class="image-section"
            >
              <div class="product-gallery">
                <!-- 主图 -->
                <div class="main-image">
                  <img
                    :src="currentImage || defaultImage"
                    :alt="currentGoods.goodsName"
                    @error="handleImageError"
                  />
                  <div class="image-zoom-btn">
                    <el-button
                      type="primary"
                      size="small"
                      circle
                      @click="showImagePreview = true"
                    >
                      <el-icon>
                        <ZoomIn />
                      </el-icon>
                    </el-button>
                  </div>
                </div>

                <!-- 缩略图 -->
                <div class="thumbnail-list">
                  <div
                    v-for="(image, index) in productImages"
                    :key="index"
                    :class="[
                      'thumbnail-item',
                      currentImage === image ? 'active' : ''
                    ]"
                    @click="currentImage = image"
                  >
                    <img
                      :src="image"
                      :alt="`${currentGoods.goodsName} ${index + 1}`"
                      @error="handleImageError"
                    />
                  </div>
                </div>
              </div>
            </el-col>

            <!-- 商品信息区域 -->
            <el-col
              :span="12"
              :xs="24"
              :sm="24"
              :md="12"
              class="info-section"
            >
              <div class="product-info">
                <!-- 商品标题和标签 -->
                <div class="product-header">
                  <h1 class="product-title">{{ currentGoods.goodsName }}</h1>
                  <div class="product-tags">
                    <el-tag
                      :type="getStatusTag(currentGoods.status)"
                      size="large"
                    >
                      {{ currentGoods.status === 0 ? '现货' : '缺货' }}
                    </el-tag>
                    <el-tag
                      type="info"
                      size="large"
                    >{{ currentGoods.goodsType }}</el-tag>
                  </div>
                </div>

                <!-- 价格信息 -->
                <div class="price-section">
                  <div class="current-price">¥{{ currentGoods.goodsMoney }}</div>
                  <div class="original-price">¥{{ (currentGoods.goodsMoney * 1.3).toFixed(2) }}</div>
                  <div class="discount-tag">
                    <el-tag
                      type="danger"
                      size="small"
                    >特价</el-tag>
                  </div>
                </div>

                <!-- 商品描述 -->
                <div class="product-description">
                  <h3>商品描述</h3>
                  <p>{{ currentGoods.goodsContent }}</p>
                </div>

                <!-- 购买选项 -->
                <div class="purchase-options">
                  <!-- 数量选择 -->
                  <div class="option-group">
                    <label class="option-label">购买数量</label>
                    <div class="quantity-selector">
                      <el-input-number
                        v-model="quantity"
                        :min="1"
                        :max="99"
                        size="large"
                      />
                      <span class="stock-info">库存充足</span>
                    </div>
                  </div>

                  <!-- 规格选择 -->
                  <div class="option-group">
                    <label class="option-label">选择规格</label>
                    <div class="size-selector">
                      <el-radio-group
                        v-model="selectedSize"
                        size="large"
                      >
                        <el-radio-button
                          v-for="size in sizes"
                          :key="size"
                          :label="size"
                        >
                          {{ size }}
                        </el-radio-button>
                      </el-radio-group>
                    </div>
                  </div>

                  <!-- 颜色选择 -->
                  <div class="option-group">
                    <label class="option-label">选择颜色</label>
                    <div class="color-selector">
                      <div
                        v-for="color in colors"
                        :key="color.name"
                        :class="[
                          'color-option',
                          selectedColor === color.name ? 'active' : ''
                        ]"
                        :style="{ backgroundColor: color.value }"
                        :title="color.name"
                        @click="selectedColor = color.name"
                      />
                    </div>
                  </div>
                </div>

                <!-- 操作按钮 -->
                <div class="action-buttons">
                  <div class="main-actions">
                    <el-button
                      type="primary"
                      size="large"
                      class="add-cart-btn"
                      :disabled="currentGoods.status !== 0"
                      @click="handleAddToCart"
                    >
                      <el-icon>
                        <ShoppingCart />
                      </el-icon>
                      加入购物车
                    </el-button>
                    <el-button
                      type="danger"
                      size="large"
                      class="buy-now-btn"
                      :disabled="currentGoods.status !== 0"
                      @click="handleBuyNow"
                    >
                      立即购买
                    </el-button>
                  </div>
                  <!-- <div class="secondary-actions">
                    <el-button
                      size="large"
                      @click="handleAddToWishlist"
                    >
                      <el-icon>
                        <Star />
                      </el-icon>
                      收藏
                    </el-button>
                    <el-button
                      size="large"
                      @click="handleShare"
                    >
                      <el-icon>
                        <Share />
                      </el-icon>
                      分享
                    </el-button>
                  </div> -->
                </div>

                <!-- 商品信息卡片 -->
                <div class="product-info-card">
                  <h3>商品信息</h3>
                  <el-descriptions
                    :column="1"
                    border
                  >
                    <el-descriptions-item label="商品编号">{{ currentGoods.id }}</el-descriptions-item>
                    <el-descriptions-item label="商品分类">{{ currentGoods.goodsType }}</el-descriptions-item>
                    <el-descriptions-item label="上架时间">{{ formatDate(currentGoods.createTime) }}</el-descriptions-item>
                    <el-descriptions-item label="创建者">{{ currentGoods.createBy || '管理员' }}</el-descriptions-item>
                  </el-descriptions>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 详情标签页 -->
        <div
          v-if="currentGoods"
          class="detail-tabs-section"
        >
          <el-tabs
            v-model="activeTab"
            class="product-tabs"
          >
            <el-tab-pane
              label="商品详情"
              name="detail"
            >
              <div class="tab-content">
                <h3>商品详细说明</h3>
                <p>{{ currentGoods.goodsContent }}</p>
                <div class="features-section">
                  <h4>产品特点</h4>
                  <el-row :gutter="24">
                    <el-col
                      :span="12"
                      :xs="24"
                      :sm="12"
                    >
                      <ul class="feature-list">
                        <li>优质材料制作，品质保证</li>
                        <li>精工细作，注重细节</li>
                        <li>时尚设计，符合现代审美</li>
                        <li>性价比高，物超所值</li>
                      </ul>
                    </el-col>
                    <el-col
                      :span="12"
                      :xs="24"
                      :sm="12"
                    >
                      <ul class="feature-list">
                        <li>环保材质，健康安全</li>
                        <li>多种规格，满足不同需求</li>
                        <li>完善售后，无忧购买</li>
                        <li>快速发货，及时到达</li>
                      </ul>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane
              label="规格参数"
              name="specs"
            >
              <div class="tab-content">
                <el-row :gutter="24">
                  <el-col
                    :span="12"
                    :xs="24"
                    :sm="12"
                  >
                    <el-card
                      shadow="never"
                      class="spec-card"
                    >
                      <template #header>
                        <h4>基本信息</h4>
                      </template>
                      <el-descriptions :column="1">
                        <el-descriptions-item label="商品名称">{{ currentGoods.goodsName }}</el-descriptions-item>
                        <el-descriptions-item label="商品分类">{{ currentGoods.goodsType }}</el-descriptions-item>
                        <el-descriptions-item label="商品状态">{{ currentGoods.status === 0 ? '正常' : '下架' }}</el-descriptions-item>
                        <el-descriptions-item label="商品价格">¥{{ currentGoods.goodsMoney }}</el-descriptions-item>
                      </el-descriptions>
                    </el-card>
                  </el-col>
                  <el-col
                    :span="12"
                    :xs="24"
                    :sm="12"
                  >
                    <el-card
                      shadow="never"
                      class="spec-card"
                    >
                      <template #header>
                        <h4>售后服务</h4>
                      </template>
                      <div class="service-list">
                        <div class="service-item">
                          <el-icon color="#67C23A">
                            <Check />
                          </el-icon>
                          <span>7天无理由退换</span>
                        </div>
                        <div class="service-item">
                          <el-icon color="#67C23A">
                            <Check />
                          </el-icon>
                          <span>全国联保</span>
                        </div>
                        <div class="service-item">
                          <el-icon color="#67C23A">
                            <Check />
                          </el-icon>
                          <span>品质保证</span>
                        </div>
                        <div class="service-item">
                          <el-icon color="#67C23A">
                            <Check />
                          </el-icon>
                          <span>正品承诺</span>
                        </div>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
              </div>
            </el-tab-pane>

            <el-tab-pane
              label="用户评价"
              name="reviews"
            >
              <div class="tab-content">
                <el-empty
                  description="暂无用户评价"
                  :image-size="120"
                >
                  <el-button type="primary">写评价</el-button>
                </el-empty>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 相关推荐 -->
        <div
          v-if="relatedProducts.length > 0"
          class="related-section"
        >
          <h2 class="section-title">相关推荐</h2>
          <el-row :gutter="24">
            <el-col
              v-for="product in relatedProducts"
              :key="product.id"
              :xs="12"
              :sm="12"
              :md="6"
              :lg="6"
              class="related-col"
            >
              <div
                class="related-card"
                @click="goToProduct(product.id)"
              >
                <div class="related-image">
                  <img
                    :src="product.goodsPic || defaultImage"
                    :alt="product.goodsName"
                    @error="handleImageError"
                  />
                </div>
                <div class="related-info">
                  <h3 class="related-title">{{ product.goodsName }}</h3>
                  <p class="related-desc">{{ product.goodsContent }}</p>
                  <div class="related-footer">
                    <span class="related-price">¥{{ product.goodsMoney }}</span>
                    <el-button
                      type="primary"
                      size="small"
                    >查看详情</el-button>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 空状态 -->
        <div
          v-if="!goodsStore.loading && !currentGoods"
          class="empty-state"
        >
          <el-empty
            description="商品不存在或已下架"
            :image-size="200"
          >
            <el-button
              type="primary"
              @click="$router.push('/goods')"
            >
              返回商品列表
            </el-button>
          </el-empty>
        </div>
      </div>
    </div>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="showImagePreview"
      :url-list="productImages"
      @close="showImagePreview = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useGoodsStore } from '@/stores/goods'
import { ElMessage } from 'element-plus'
import {
  ArrowRight,
  ZoomIn,
  ShoppingCart,
  Star,
  Share,
  Check
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const goodsStore = useGoodsStore()

// 响应式数据
const quantity = ref(1)
const selectedSize = ref('M')
const selectedColor = ref('黑色')
const activeTab = ref('detail')
const currentImage = ref('')
const showImagePreview = ref(false)

// 默认图片
const defaultImage =
  'https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=600&h=600&fit=crop'

// 当前商品
const currentGoods = computed(() => goodsStore.currentGoods)

// 商品图片
const productImages = computed(() => {
  const images = []
  if (currentGoods.value?.goodsPic) {
    images.push(currentGoods.value.goodsPic)
  }
  // 添加一些演示图片
  const demoImages = [
    'https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=600&h=600&fit=crop',
    'https://images.unsplash.com/photo-1523275335684-37898b6baf30?w=600&h=600&fit=crop',
    'https://images.unsplash.com/photo-1526170375885-4d8ecf77b99f?w=600&h=600&fit=crop',
    'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=600&h=600&fit=crop'
  ]

  if (images.length === 0) {
    images.push(...demoImages)
  } else {
    // 确保至少有4张图片用于展示
    while (images.length < 4) {
      images.push(...demoImages.slice(0, 4 - images.length))
    }
  }

  return images.slice(0, 4)
})

// 相关推荐商品
const relatedProducts = computed(() => {
  if (!currentGoods.value) return []

  return goodsStore.goodsList
    .filter(
      (item) =>
        item.goodsType === currentGoods.value?.goodsType &&
        item.id !== currentGoods.value?.id &&
        item.status === 0
    )
    .slice(0, 4)
})

// 规格选项
const sizes = ['XS', 'S', 'M', 'L', 'XL', 'XXL']
const colors = [
  { name: '黑色', value: '#000000' },
  { name: '白色', value: '#FFFFFF' },
  { name: '红色', value: '#EF4444' },
  { name: '蓝色', value: '#3B82F6' },
  { name: '绿色', value: '#10B981' },
  { name: '灰色', value: '#6B7280' }
]

// 方法
const getStatusTag = (status: number) => {
  return status === 0 ? 'success' : 'danger'
}

const handleAddToCart = () => {
  ElMessage.success(`已将 ${quantity.value} 件商品加入购物车`)
}

const handleBuyNow = () => {
  ElMessage.success('立即购买功能开发中')
}

const handleAddToWishlist = () => {
  ElMessage.success('已加入收藏夹')
}

const handleShare = () => {
  if (navigator.share) {
    navigator.share({
      title: currentGoods.value?.goodsName,
      text: currentGoods.value?.goodsContent,
      url: window.location.href
    })
  } else {
    navigator.clipboard.writeText(window.location.href)
    ElMessage.success('链接已复制到剪贴板')
  }
}

const goToProduct = (id: number) => {
  router.push(`/goods/${id}`)
}

const handleImageError = (event: Event) => {
  const target = event.target as HTMLImageElement
  target.src = defaultImage
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 监听路由参数变化
watch(
  () => route.params.id,
  async (newId) => {
    if (newId) {
      const id = parseInt(newId as string, 10)
      await goodsStore.fetchGoodsDetail(id)

      // 更新当前图片
      if (currentGoods.value?.goodsPic) {
        currentImage.value = currentGoods.value.goodsPic
      } else {
        currentImage.value = productImages.value[0]
      }
    }
  },
  { immediate: true }
)

// 生命周期
onMounted(async () => {
  // 如果商品列表为空，先获取商品列表
  if (goodsStore.goodsList.length === 0) {
    await goodsStore.fetchGoodsList()
  }

  // 设置默认图片
  if (currentGoods.value?.goodsPic) {
    currentImage.value = currentGoods.value.goodsPic
  } else {
    currentImage.value = productImages.value[0]
  }
})
</script>

<style scoped>
.goods-detail-view {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 面包屑导航 */
.breadcrumb-section {
  background: white;
  border-bottom: 1px solid #ebeef5;
  padding: 16px 0;
}

/* 主要内容 */
.main-content {
  padding: 32px 0;
}

.product-section {
  margin-bottom: 48px;
}

/* 图片区域 */
.image-section {
  margin-bottom: 32px;
}

.product-gallery {
  position: sticky;
  top: 100px;
}

.main-image {
  position: relative;
  width: 100%;
  height: 500px;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.main-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-zoom-btn {
  position: absolute;
  top: 16px;
  right: 16px;
}

.thumbnail-list {
  display: flex;
  gap: 12px;
}

.thumbnail-item {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

.thumbnail-item:hover,
.thumbnail-item.active {
  border-color: #409eff;
}

.thumbnail-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 商品信息区域 */
.info-section {
  margin-bottom: 32px;
}

.product-info {
  background: white;
  border-radius: 12px;
  padding: 32px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.product-header {
  margin-bottom: 24px;
}

.product-title {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 16px;
  line-height: 1.4;
}

.product-tags {
  display: flex;
  gap: 12px;
}

.price-section {
  display: flex;
  align-items: baseline;
  gap: 16px;
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #ebeef5;
}

.current-price {
  font-size: 36px;
  font-weight: 700;
  color: #e74c3c;
}

.original-price {
  font-size: 18px;
  color: #909399;
  text-decoration: line-through;
}

.product-description {
  margin-bottom: 32px;
}

.product-description h3 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}

.product-description p {
  color: #606266;
  line-height: 1.6;
}

.purchase-options {
  margin-bottom: 32px;
}

.option-group {
  margin-bottom: 24px;
}

.option-label {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}

.quantity-selector {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stock-info {
  color: #67c23a;
  font-size: 14px;
}

.color-selector {
  display: flex;
  gap: 12px;
}

.color-option {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 3px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.color-option:hover,
.color-option.active {
  border-color: #409eff;
  transform: scale(1.1);
}

.color-option.active::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 16px;
  height: 16px;
  background: white;
  border-radius: 50%;
  border: 2px solid #409eff;
}

.action-buttons {
  margin-bottom: 32px;
}

.action-buttons .main-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.add-cart-btn,
.buy-now-btn {
  flex: 1;
  height: 48px;
  font-size: 16px;
}

.secondary-actions {
  display: flex;
  gap: 12px;
}

.secondary-actions .el-button {
  flex: 1;
  height: 44px;
}

.product-info-card h3 {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
}

/* 详情标签页 */
.detail-tabs-section {
  background: white;
  border-radius: 12px;
  padding: 32px;
  margin-bottom: 48px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.tab-content h3 {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
}

.tab-content h4 {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}

.features-section {
  margin-top: 32px;
}

.feature-list {
  list-style: none;
  padding: 0;
}

.feature-list li {
  position: relative;
  padding-left: 24px;
  margin-bottom: 12px;
  color: #606266;
  line-height: 1.6;
}

.feature-list li::before {
  content: '✓';
  position: absolute;
  left: 0;
  color: #67c23a;
  font-weight: bold;
}

.spec-card {
  margin-bottom: 24px;
}

.service-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.service-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

/* 相关推荐 */
.related-section {
  background: white;
  border-radius: 12px;
  padding: 32px;
  margin-bottom: 48px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 24px;
}

.related-col {
  margin-bottom: 24px;
}

.related-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.related-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.related-image {
  width: 100%;
  height: 180px;
  overflow: hidden;
}

.related-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.related-info {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.related-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.related-desc {
  color: #606266;
  font-size: 14px;
  margin-bottom: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.related-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.related-price {
  font-size: 18px;
  font-weight: 700;
  color: #e74c3c;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    padding: 16px 0;
  }

  .product-gallery {
    position: static;
  }

  .main-image {
    height: 300px;
  }

  .product-info {
    padding: 24px;
  }

  .product-title {
    font-size: 24px;
  }

  .current-price {
    font-size: 28px;
  }

  .secondary-actions {
    flex-direction: column;
  }

  .detail-tabs-section {
    padding: 24px;
  }

  .related-section {
    padding: 24px;
  }
}
</style> 